//
//  CZOAuthViewController.swift
//  Weibo30
//
//  Created by apple on 16/8/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//  微博AppKey
let WeiboAppKey = "3165859311"
//  微博AppSecret
let WeiboAppSecret = "c495c40b528ffc1e29045073b4b1da71"
//  授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"

class CZOAuthViewController: UIViewController {

    //  MARK:   -- 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //  改成透明的
        webView.opaque = false
        //  设置代理
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavUI()
        requestOAuthLogin()
        
    }
    
    private func setNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
        navigationItem.title = "微博登录"
    
    }
    
    //  MARK:   --点击事件
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func autoFillAction() {
        
//        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '15910871727';document.getElementById('passwd').value = 'cc13579cc'")
        //webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '15845652122';document.getElementById('passwd').value = 'tangshuai'")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123'")
    }
    
    
    //  请求第三方登录页面
    private func requestOAuthLogin() {
        //  准备url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        print(url)
        
        //  准备urlRequest
        let urlRequest = NSURLRequest(URL: NSURL(string: url)!)
        
        //  通过webView加载页面
        webView.loadRequest(urlRequest)
        
        
        
    
    }
    
    //  代码已经抽取CZUserViewModel里面
    
    //  通过code获取accesstoken
//    private func reqeustAccessTokenWithCode(code: String) {
//        
//        CZNetworkTools.sharedTools.reqeustAccessTokenWithCode(code) { (response, error) -> () in
//            if error != nil {
//                print("网络请求失败\(error)")
//                return
//            }
//            
//            //  代码执行到此网络请求成功
//            
//            //  判断服务端给的数据是否是一个正确的字典
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的字典格式")
//                return
//            }
//            //  代码执行到此,字典没有问题
//            let userAccount = CZUserAccount(dic: dic)
//            print(userAccount.access_token)
//            //  请求用户基本信息
//            self.requestUserInfo(userAccount)
//
//            
//            
//            
//            
//        }
//        
//        
//        
//        
//        
////        //  准备url
////        let url = "https://api.weibo.com/oauth2/access_token"
////        //  准备参数
////        let params = [
////            "client_id": WeiboAppKey,
////            "client_secret": WeiboAppSecret,
////            "grant_type": "authorization_code",
////            "code": code,
////            "redirect_uri": WeiboRedirect_Uri
////        ]
////
////        //  创建sessionManager
////        let sessionManager = AFHTTPSessionManager()
////        //  添加响应可接受的类型
////        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        sessionManager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            //  判断服务端给的数据是否是一个正确的字典
////            guard let dic = response as? [String: AnyObject] else {
////                print("不是一个正确的字典格式")
////                return
////            }
////            //  代码执行到此,字典没有问题
////            let userAccount = CZUserAccount(dic: dic)
////            print(userAccount.access_token)
////            //  请求用户基本信息
////            self.requestUserInfo(userAccount)
////           
////            
////            }) { (_, error) -> Void in
////                
////                print(error)
////                
////        }
//        
//    
//    }
    
    //  通过accesstoken和uid获取用户信息
//    private func requestUserInfo(userAccount: CZUserAccount) {
//        
//        CZNetworkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
//            
//            if error != nil {
//                print("网络请求失败, \(error)")
//                return
//            }
//            
//            //  代码执行到此,表示网络请求成功
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的字典格式")
//                return
//            }
//            
//            //  代码执行到此,表示字典没有问题
//            let name = dic["name"]
//            let avatar_large = dic["avatar_large"]
//
//            userAccount.name = name as? String
//            userAccount.avatar_large = avatar_large as? String
//
//            print(userAccount)
//
//            //  表示用户登录成功
//            //  保存用户账号的模型
//            userAccount.saveUserAccount()
//            
//        }
//        
//        
//        
//        
//        
//        
//        
////        //  准备url
////        let url = "https://api.weibo.com/2/users/show.json"
////        //  准备参数
////        let params = [
////            "access_token": userAccount.access_token!,
////            "uid": "\(userAccount.uid)"
////        ]
////        
////        let path = url + "?access_token=" + userAccount.access_token! + "&uid=" + "\(userAccount.uid)"
////        print("--" + path)
////        
////        //  创建sessionManager对象
////        let sessionManager = AFHTTPSessionManager()
////        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        //  发送get请求
////        sessionManager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            //  判断服务端给的数据是否是一个正确的json数据
////            guard let dic = response as? [String: AnyObject] else {
////                print("不是一个正确的字典格式")
////                return
////            }
////            
////            //  代码执行到此,字典没有问题
////            let name = dic["name"]
////            let avatar_large = dic["avatar_large"]
////            
////            userAccount.name = name as? String
////            userAccount.avatar_large = avatar_large as? String
////            
////            print(userAccount)
////            
////            //  表示用户登录成功
////            //  保存用户账号的模型
////            userAccount.saveUserAccount()
////            
////            
////            
////            }) { (_, error) -> Void in
////                print(error)
////        }
//    
//    
//    }
    


}

//  MARK: -UIWebViewDelegate 代理
extension CZOAuthViewController: UIWebViewDelegate {

    //  将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL?.absoluteString)
        
        guard let url = request.URL else {
            return false
        }
        
        //  代码执行到此,url一定有值
        
        //  不是以回调页打头, 我不需要关心
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        //  代码执行到此,是我们的回调页打头
        
        if let query = url.query where query.hasPrefix("code=") {
            //  获取code
            print(query)
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            //  获取accesstoken
//            reqeustAccessTokenWithCode(code)
            
            CZUserAccountViewModel.sharedUserAccount.reqeustAccessTokenWithCode(code, callBack: { (isSuccess) -> () in
                
                if isSuccess {
                    print("登录成功")
                    //  切换根视图控制器需要在线dismis完成以后闭包里面, 要不然能present这个控制器不能释放
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                    
                    
                    
                    
                } else {
                    print("登录失败")
                }
                
                
            })
            
            
        } else {
            
            dismissViewControllerAnimated(true, completion: nil)
        
        }
        
        return false
    }
    
    //  开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //  加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //  加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    
    
}


















